package pres.lnk.learn.designpattern.m_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * <p>动态代理</p>
 * <pre>
 * 利用JDK的API动态生成代理对象，不用实现被代理对象的接口，甚至可以代理多个有相同代理操作的类
 * </pre>
 * @Author lnk
 * @Date 2018/4/10
 */
public class UserDaoDynamicProxy implements InvocationHandler {

    /**
     * 被代理对象
     */
    private UserDao target;

    public UserDaoDynamicProxy(UserDao target) {
        this.target = target;
    }

    public UserDao getProxy(){
        UserDao proxy = (UserDao) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
        return proxy;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        /*
         * 动态代理会代理接口所有方法
         */
        String methodName = method.getName();
        Object result = null;
        if(methodName.startsWith("select")){
            result = method.invoke(target, args);
        } else {
            System.out.println("open the transaction");
            result = method.invoke(target, args);
            System.out.println("commit the transaction");
        }
        return result;
    }
}
